package com.java.schedule.springbatch.config;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

//@Configuration
//@MapperScan(basePackages = "com.java.schedule.springbatch.mapper.from", sqlSessionFactoryRef = "fromSqlSessionFactory")
public class DatasourceFromConfigbak {
    private static final Logger logger = LoggerFactory.getLogger(DatasourceFromConfigbak.class);

    @Value("${spring.datasource1.url}")
    private String url;

    @Value("${spring.datasource1.username}")
    private String username;

    @Value("${spring.datasource1.password}")
    private String password;

    @Value("${spring.datasource1.driverClassName}")
    private String driverClassName;

    @Bean("fromDataSource") // 声明其为Bean实例
    @Primary // 在同样的DataSource中，首先使用被标注的DataSource
    public DataSource dataSource() {
        HikariDataSource datasource = new HikariDataSource();
        datasource.setJdbcUrl(this.url);
        datasource.setUsername(this.username);
        datasource.setPassword(this.password);
        datasource.setDriverClassName(driverClassName);
        return datasource;
    }

    @Bean("fromSqlSessionFactory")
    @Primary
    public SqlSessionFactory fromSqlSessionFactory(@Qualifier("fromDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        // mapper的xml形式文件位置必须要配置，不然将报错：no statement （这种错误也可能是mapper的xml中，namespace与项目的路径不一致导致）
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/EmployeeFromMapper.xml"));
        return bean.getObject();
    }

    @Bean("irpSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate fromSqlSessionTemplate(@Qualifier("fromSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
